from sqlalchemy.orm import Session
from sqlalchemy import text
from datetime import datetime

def get_weather_by_time(db: Session, time: datetime):
    """
    查询在指定时间点之前（或恰好在该时间点）的、最近的一条天气记录。
    """
    query = text("""
        SELECT 
            dt, winddirect, windspeed, mintemp, humidity, 
            air, airlevel, maxtemp, rain
        FROM weather
        WHERE dt <= :request_time
        ORDER BY dt DESC
        LIMIT 1;
    """)
    
    result = db.execute(query, {"request_time": time})
    
    return result.fetchone() # 只返回一行或 None